<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="back"></i>
      <p>在线支付</p>
    </header>
    <!-- 订单信息部分 -->
    <h3>订单信息：</h3>
    <div class="order-info">
      <p>
        {{ orders.business.businessName }}
        <i class="fa fa-caret-down" @click="detailetShow"></i>
      </p>
      <p>&#165;{{ orders.orderTotal }}</p>
    </div>
    <!-- 订单明细部分 -->
    <ul class="order-detailet" v-show="isShowDetailet">
      <li v-for="item in orders.list" :key="item.id">
        <p>{{ item.food.foodName }} x {{ item.quantity }}</p>
        <p>&#165;{{ item.food.foodPrice * item.quantity }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&#165;{{ orders.business.deliveryPrice }}</p>
      </li>
      <li>
        <p>积分</p>
        <p>-&#165;{{ reduction }}</p>
      </li>
    </ul>
    <!-- 支付方式部分 -->
    <ul class="payment-type">
      <li @click="selectPaymentMethod('alipay')">
        <img src="../assets/alipay.png">
        <i class="fa fa-check-circle" v-if="selectedPaymentMethod === 'alipay'"></i>
      </li>
      <li @click="selectPaymentMethod('wechat')">
        <img src="../assets/wechat.png">
        <i class="fa fa-check-circle" v-if="selectedPaymentMethod === 'wechat'"></i>
      </li>
    </ul>
    <div class="payment-button">
      <button :style="{ backgroundColor: isPayed ? 'gray' : '#38CA73' }" @click="pay">确认支付</button>
    </div>
    <h2 v-show="paySuccess" style="color: #0097FF; text-align: center;">
      支付成功！
    </h2>
    <!-- 底部菜单部分 -->
    <Footer />
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import qs from 'qs';
import Footer from '../components/Footer.vue';

export default {
  name: 'Payment',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const orderId = ref(route.query.orderId);
    const userId = ref(route.query.userId);
    const reduction = ref(route.query.reduction);
    const orders = ref({ business: {} });
    const isShowDetailet = ref(false);
    const paySuccess = ref(false);
    const isPayed = ref(false);
    const selectedPaymentMethod = ref('alipay'); // 默认选中支付宝

    onMounted(() => {
      fetchOrdersById();
      // 阻止后退
      history.pushState(null, null, document.URL);
      window.onpopstate = () => {
        router.push('/index');
      };
    });

    onUnmounted(() => {
      window.onpopstate = null;
    });

    const fetchOrdersById = async () => {
      try {
		let url=`OrdersController/getOrdersById/${orderId.value}`
        const response = await axios.get(url, {}, {
			headers: {
				'Content-Type': 'application/json'
			}
		});
        orders.value = response.data.result;
      } catch (error) {
        console.error(error);
      }
    };

    const detailetShow = () => {
      isShowDetailet.value = !isShowDetailet.value;
    };

    const selectPaymentMethod = (method) => {
      selectedPaymentMethod.value = method;
    };

     const pay = async () => {
          if (!selectedPaymentMethod.value) {
            alert('请选择支付方式');
            return;
          }
          try {
    		let url=`WalletController/pay/${orderId.value}`
            const response = await axios.post(url,{}, {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              }
            });
            const orderIdResponse = response.data.result;
            if (orderIdResponse > 0) {
              paySuccess.value = true;
              isPayed.value = true;
    		  try {
    			  let url=`WalletController/pay/${orderId.value}`
    		      const response = await axios.post(url, {}, {
    		          headers: {
    		            'Content-Type': 'application/json'
    		          }
    		        });
    		      const orderIdResponse = response.data.result;
    		      if (orderIdResponse > 0) {
                paySuccess.value = true;
                isPayed.value = true;

    		        // 调用后端接口扣除积分
    		        try {
    					let deductpointNum= parseInt(reduction.value*10)
    					let deductUrl=`CreditController/use/${userId.value}/${deductpointNum}`
    		          const deductPointsResponse  = await axios.post(deductUrl, {}, {
    					headers: {
    						'Content-Type': 'application/json'
    					}
    				});
    		          if (deductPointsResponse.data.result == "Points used successfully") {
    		            // 积分扣除成功，导航到订单列表或其他页面
    		            router.push('/orderList'); // 假设 '/orderList' 是订单列表的路由路径
    		          } 
    		        } catch (error) {
    		          console.error('扣除积分错误:', error);
    		          alert('扣除积分时发生错误');
    		        }
    		  
    		        setTimeout(() => {
    		          router.push('/orderList');
    		        }, 500);
    		      } else {
    		        alert('支付失败！');
    		      }
    		    } catch (error) {
    		      console.error('支付错误:', error);
    		      alert('支付时发生错误');
    		    }
              // 调用后端接口积累积分
              try {
    			  let addpointNum=parseInt(orders.value.orderTotal/10)
    			  let addUrl=`CreditController/add/${userId.value}/${addpointNum}`
                const addPointsResponse = await axios.post(addUrl, {}, {
    				headers: {
    					'Content-Type': 'application/json'
    				}
    			});
                if (addPointsResponse.data.result == "Points added successfully") {
                  // 积分添加成功，导航到订单列表或其他页面
                  router.push('/orderList'); // 假设 '/orderList' 是订单列表的路由路径
                } 
              } catch (error) {
                console.error('添加积分错误:', error);
                alert('添加积分时发生错误');
              }
    
              setTimeout(() => {
                router.push('/orderList');
              }, 500);
            } else {
              alert('支付失败！');
            }
          } catch (error) {
            console.error('支付错误:', error);
            alert('支付时发生错误');
          }
        };

    const back = () => {
      router.back();
    };

    return {
      orders,
      isShowDetailet,
      detailetShow,
      pay,
      isPayed,
      paySuccess,
      selectedPaymentMethod,
      selectPaymentMethod,
      back
    };
  },
  components: {
    Footer
  }
};
</script>

<style scoped>
  /****************** 总容器 ******************/
  .wrapper {
    width: 100%;
    height: 100%;
  }

  /****************** header部分 ******************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #01B0F2;
    font-size: 4.8vw;
    color: #fff;

    z-index: 10;

    display: flex;
    justify-content: flex-start;
    align-items: center;

    position: fixed;
    left: 0;
    top: 0;
  }

  .wrapper header i {
    margin: 0vw 0vw 0vw 3vw;
    font-size: 6vw;
    user-select: none;
    cursor: pointer;
  }

  .wrapper header p {
    margin: 0vw 0vw 0vw 33.5vw;
  }

  /****************** 订单信息部分 ******************/
  .wrapper h3 {
    margin-top: 12vw;
    box-sizing: border-box;
    padding: 4vw 4vw 0;
    font-size: 4vw;
    font-weight: 300;
    color: #999;
  }

  .wrapper .order-info {
    box-sizing: border-box;
    padding: 4vw;
    font-size: 4vw;
    color: #666;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .order-info p:last-child {
    color: orangered;
  }

  /****************** 订单明细部分 ******************/
  .wrapper .order-detailet {
    width: 100%;
  }

  .wrapper .order-detailet li {
    width: 100%;
    box-sizing: border-box;
    padding: 1vw 4vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .order-detailet li p {
    font-size: 3vw;
    color: #666;
  }

  /****************** 支付方式部分 ******************/
  .wrapper .payment-type {
    width: 100%;
  }

  .wrapper .payment-type li {
    width: 100%;
    box-sizing: border-box;
    padding: 4vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .payment-type li img {
    width: 33vw;
    height: 8.9vw;
  }

  .wrapper .payment-type li .fa-check-circle {
    font-size: 5vw;
    color: #38CA73;
  }

  .wrapper .payment-button {
    width: 100%;
    box-sizing: border-box;
    padding: 4vw;
  }

  .wrapper .payment-button button {
    width: 100%;
    height: 10vw;
    border: none;
    font-size: 3vw;
    /*去掉外轮廓线*/
    outline: none;
	border-radius: 4px;
	color: #fff;
}
</style>

